import vue from '@vitejs/plugin-vue';
import { defineConfig, normalizePath } from 'vite';
import cesium from 'vite-plugin-cesium';
import { viteStaticCopy } from 'vite-plugin-static-copy';
import path from 'path';
import fs from 'fs';
import dotenv from 'dotenv';

// 路径解析函数
function resolve(dir: string) {
  return path.resolve(__dirname, dir);
}

// 获取本地时间格式的函数
function getLocalTimeString() {
  const now = new Date();
  
  // 获取本地时间组件
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

export default defineConfig(({ command }) => {
  // 仅在构建生产包时更新构建时间
  if (command === 'build') {
    const envPath = path.resolve(__dirname, '.env');
    
    try {
      // 1. 读取现有环境变量
      const envConfig = dotenv.parse(fs.readFileSync(envPath));
      
      // 2. 更新构建时间（使用本地时间）
      envConfig.VITE_APP_LAST_BUILD_TIME = getLocalTimeString();
      
      // 3. 写回.env文件
      const updatedContent = Object.entries(envConfig)
        .map(([key, value]) => `${key}=${value}`)
        .join('\n');
      fs.writeFileSync(envPath, updatedContent);
      
      console.log(`✅ 更新构建时间: ${envConfig.VITE_APP_LAST_BUILD_TIME}`);
    } catch (error) {
      console.error('❌ 更新构建时间失败:', error.message);
    }
  }

  return {
    base: './',
    build: {
      outDir: "./dist/editor"
    },
    resolve: {
      alias: {
        '@': resolve('src'),
        cesium: path.resolve(__dirname, 'node_modules/cesium/Source/Cesium')
      }
    },
    plugins: [
      vue(),
      cesium({"cesiumBaseUrl":"../cesium"}),
      viteStaticCopy({
        targets: [
          {
            src: normalizePath(path.resolve(__dirname, './node_modules/earthsdk3-assets')),
            dest: '../js'
          }
        ]
      })
    ],
  }
})